<template>
  <div class="category-manage">
    <div class="page-header">
      <h1>分类管理</h1>
      <p>管理图书分类</p>
    </div>

    <el-card>
      <div class="table-header">
        <h3>分类列表</h3>
        <div class="header-actions">
          <el-input
            v-model="searchName"
            placeholder="搜索分类名称"
            style="width: 200px; margin-right: 16px"
            clearable
            @input="loadCategories"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加分类
          </el-button>
        </div>
      </div>
      
      <el-table :data="categories" v-loading="loading" row-key="id">
        <el-table-column label="分类名称" prop="name" />
        <el-table-column label="描述" prop="description" show-overflow-tooltip />
        <el-table-column label="排序" prop="sort" width="80" />
        <el-table-column label="创建时间" prop="createTime" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editCategory(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteCategory(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="categoryForm"
        :model="categoryData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="categoryData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="categoryData.sort"
            :min="0"
            :max="9999"
            placeholder="排序值"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import request from '@/utils/request'

const loading = ref(false)
const categories = ref([])
const searchName = ref('')

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const submitting = ref(false)
const categoryForm = ref(null)

// 表单数据
const categoryData = reactive({
  id: null,
  name: '',
  description: '',
  sort: 0
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述不能超过 200 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { min: 0, max: 9999, message: '排序值在 0 到 9999 之间', trigger: 'blur' }
  ]
}

// 加载分类数据
const loadCategories = async () => {
  loading.value = true
  try {
    const params = {}
    if (searchName.value) {
      params.name = searchName.value
    }
    
    const response = await request.get('/categories/list', { params })
    categories.value = response.data || []
  } catch (error) {
    console.error('加载分类数据失败:', error)
    ElMessage.error('加载分类数据失败')
  } finally {
    loading.value = false
  }
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加分类'
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 编辑分类
const editCategory = (category) => {
  dialogTitle.value = '编辑分类'
  isEdit.value = true
  dialogVisible.value = true
  
  // 填充表单数据
  Object.assign(categoryData, {
    id: category.id,
    name: category.name,
    description: category.description || '',
    sort: category.sort || 0
  })
}

// 删除分类
const deleteCategory = async (category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${category.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await request.delete(`/categories/${category.id}`)
    ElMessage.success('删除成功')
    loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除分类失败:', error)
      ElMessage.error((error.response && error.response.data && error.response.data.message) || '删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await categoryForm.value.validate()
    submitting.value = true
    
    const data = {
      name: categoryData.name,
      description: categoryData.description,
      sort: categoryData.sort
    }
    
    if (isEdit.value) {
      // 更新分类
      await request.put(`/categories/${categoryData.id}`, data)
      ElMessage.success('更新成功')
    } else {
      // 添加分类
      await request.post('/categories', data)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
    loadCategories()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error((error.response && error.response.data && error.response.data.message) || '操作失败')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(categoryData, {
    id: null,
    name: '',
    description: '',
    sort: 0
  })
  
  if (categoryForm.value) {
    categoryForm.value.clearValidate()
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 24px;
  color: #333;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 